package cn.huhst.cas.weisiqian.web;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import cn.huhst.cas.weisiqian.pojo.News;
import cn.huhst.cas.weisiqian.service.NewsService;

@WebServlet("/ListNews.do")
public class ListNews extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(ListNews.class);
	private NewsService newsservice = null;

	public ListNews() {
		super();
		newsservice = new NewsService();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String strpageIndex = request.getParameter("pageindex");
		String strpageSize = request.getParameter("pagesize");
		int pageIndex = 1;
		int pageSize = 10;
		int count = 0;
		int maxPageSize = 1;
		if (strpageSize != null && !"".equals(strpageSize)) {
			int temPageSize = Integer.parseInt(strpageSize);
			pageSize = temPageSize < 1 ? 10 : temPageSize;
		}
		count = newsservice.getNewsCount();
		maxPageSize = (count % pageSize) > 0 ? (count / pageSize + 1) : (count / pageSize);
		if (strpageIndex != null && !"".equals(strpageIndex)) {
			int temPageIndex = Integer.parseInt(strpageIndex);
			pageIndex = temPageIndex < 1 ? 1 : (temPageIndex > maxPageSize ? maxPageSize : temPageIndex);
		}

		HttpSession session = request.getSession();
		session.setAttribute("pageIndex", pageIndex);
		session.setAttribute("pageSize", pageSize);
		session.setAttribute("maxPageSize", maxPageSize);
		session.setAttribute("count", count);
		logger.info("pageIndex=" + pageIndex + " pageSize=" + pageSize);
		ArrayList<News> allNews = newsservice.getNews(pageIndex, pageSize);
		session.setAttribute("allNews", allNews);
		request.getRequestDispatcher("newslist_admin.jsp").forward(request, response);
	}

}
